package com.livegoods.service;

import com.livegoods.BuyactionApplication;
import com.livegoods.LivegoodsBuyMessage;
import com.livegoods.LivegoodsMessage;
import com.livegoods.message.LivegoodsMessagePublisher;
import com.livegoods.pojo.House;
import com.livegoods.pojo.LivegoodsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class BuyactionServiceImpl  implements BuyactionService {

    /**
     *
     * 商品预定方法
     *
     * 1，从Redis获取商品缓存信息
     *
     * 2，发送消息到Rabbitmq中（监听方监听接受消息，消费消息，开始执行抢购功能），并且接受返回结果
     *  结果
     *      1，预定抢购成功
     *      2，预定抢购失败
     *
     * @param id
     * @param user
     * @return
     */

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LivegoodsMessagePublisher livegoodsMessagePublisher;

    @Value("${livegoods.buyaction.exchange}")
    private String livegoodsRabbitmqexchange;
    @Value("${livegoods.buyaction.routingKey}")
    private String livegoodsRabbitmqroutingKey;



    @Override
    public LivegoodsResult buyaction(String id, String user) {


        String key = "livegoods::"+id;
        //1，从Redis获取商品缓存信息,判断是否已经被预定了（或者商品还有数量）
        House house = (House) redisTemplate.opsForValue().get(key);

        //1.1判断 isRented是否为true，为true，已经有人租了
        if(house.isRented()){
            return LivegoodsResult.error("手慢了，此房间已经被预定了...");
        }

        //2.创建消息对象
        LivegoodsBuyMessage livegoodsBuyMessage = new LivegoodsBuyMessage();
        livegoodsBuyMessage.setId(id);//商品id
        livegoodsBuyMessage.setUser(user);//用户

        //3.创建消息发送对象，发送消息,接受预定结果：boolean类型
        boolean result = (boolean)livegoodsMessagePublisher.sendMessageSync(livegoodsRabbitmqexchange, livegoodsRabbitmqroutingKey, livegoodsBuyMessage);

        //返回失败结果
        if(!result){
            return LivegoodsResult.error("手慢了，此房间已经被预定了...");
        }else{
            LivegoodsResult ok = LivegoodsResult.ok();
            ok.setMsg("恭喜您，预定成功");
            return ok;

        }

    }
}
